const App = getApp();
// 工具类
const util = require('../../utils/util.js');
Page({
  data: {
    // 搜索框样式
    searchColor: "rgba(0,0,0,0.4)",
    searchSize: "15",
    searchName: "搜索商品",

    // 列表高度
    scrollHeight: 0,

    // 一级分类：指针
    curNav: true,
    curIndex: 0,

    // 分类列表
    list: [],

    // show
    notcont: false,
  
    // 商品
    category_id: 0,
    // 商品列表
    GoodsList: [],
    page: 1, // 当前页码
    no_more: false, // 没有更多数据
    isLoading: true, // 是否正在加载中
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad() {
    let _this = this;
    // 设置分类列表高度
    _this.setListHeight();
    // 获取分类列表
    _this.getCategoryList();
    
  },
  onShow(){
    if(App.globalData.goods_tab == 'douyin'){
      this.setData({
        category_id : 6,
        curIndex:6
      })
      this.getGoodsList();
    }
    // 加载购物车
    this.getCartList()
  },
  /**
   * 设置分类列表高度
   */
  setListHeight() {
    let _this = this;
    wx.getSystemInfo({
      success: function(res) {
        _this.setData({
          scrollHeight: res.windowHeight - 47,
        });
      }
    });
  },
  onGoodsClick(e){
    wx.navigateTo({
      url: '/pages/goods/index?goods_id='+e.currentTarget.dataset.id,
    })
  },
  /**
   * 获取分类列表
   */
  getCategoryList() {
    let _this = this;
    App._get('category/index', {}, result => {
      let data = result.data;
      _this.setData({
        list: data.list,
        templet: data.templet,
        curNav: data.list.length > 0 ? data.list[0].category_id : true,
        notcont: !data.list.length
      });
      // 获取商品分类
      if (data.templet.category_style == 20) {
        _this.getGoodsList();
      }
      //_this.getGoodsList();
    });
  },
  /**
   * Api：获取商品列表
   */
  getGoodsList(isPage, page) {
    let _this = this;
    let index = _this.data.curIndex;
    let category_id = _this.data.list[index]['category_id'];
    App._get('goods/lists', {
      page: page || 1,
      category_id: category_id
    }, function (result) {
      let resList = result.data.list,
        dataList = _this.data.GoodsList;
      if (isPage == true) {
        _this.setData({
          'GoodsList.data': dataList.data.concat(resList.data),
          isLoading: false,
        });
      } else {
        _this.setData({
          GoodsList: resList,
          isLoading: false,
        });
      }
      // 加载购物车
      _this.getCartList()
    });
  },
  /**
   * 下拉到底加载数据
   */
  bindDownLoad() {
    // 已经是最后一页
    if (this.data.page >= this.data.GoodsList.last_page) {
      this.setData({
        no_more: true
      });
      return false;
    }
    // 加载下一页列表
    this.getGoodsList(true, ++this.data.page);
  },
  /**
   * 一级分类：选中分类
   */
  selectNav(e) {
    let _this = this;
    _this.setData({
      curNav: e.target.dataset.id,
      curIndex: parseInt(e.target.dataset.index),
      scrollTop: 0
    });
    // 第二步：更新当前的商品列表
    _this.getGoodsList();
  },

  /**
   * 设置分享内容
   */
  onShareAppMessage() {
    let _this = this;
    return {
      title: _this.data.templet.share_title,
      path: '/pages/category/index?' + App.getShareUrlParams()
    };
  },
 /**
   * 步进器增加
   */
  onPlus(event){
    let goods_num = 0;
    let goods_id = event.currentTarget.dataset.goodsId;
    let goods_sku_id = event.currentTarget.dataset.goodsSkuId;
    let arr = this.data.GoodsList.data
    let addGoods = false
    arr.forEach(item => {
      if (item.goods_id == goods_id) {
        if(item.goods_num){
          addGoods = false
        }else{
          addGoods = true
        }
        item.showMinus = true
      }
    })
    // 添加到后台购物车
    // 后端同步更新
    wx.showLoading({
      title: '加载中',
      mask: true
    });
    if(addGoods){
      App._post_form('cart/add', {
        goods_id: goods_id,
        goods_num: 1,
        goods_sku_id: goods_sku_id,
      }, (response) => {
        // App.showSuccess(result.msg);
        if(response.code == 1){
          arr.forEach(item => {
            if (item.goods_id == goods_id) {
              if(item.goods_num){
                item.goods_num = item.goods_num +  1
              }else{
                item.goods_num = goods_num +  1
              }
              goods_num = item.goods_num;
              item.showMinus = true
            }
          })
          this.setData({
            'GoodsList.data': arr
          })
          this.getCartList()
        }
      }, null, () => {
        wx.hideLoading();
      });
    }else{
      App._post_form( 'cart/add' , {
        goods_id: goods_id,
        goods_num: 1,
        goods_sku_id: goods_sku_id,
      }, (response) => {
        // App.showSuccess(result.msg);
        if(response.code == 1){
          arr.forEach(item => {
            if (item.goods_id == goods_id) {
              if(item.goods_num){
                item.goods_num = item.goods_num +  1
              }else{
                item.goods_num = goods_num +  1
              }
              goods_num = item.goods_num;
              item.showMinus = true
            }
          })
          this.setData({
            'GoodsList.data': arr
          })
          this.getCartList()
        }
      }, null, () => {
        wx.hideLoading();
      });
    }
    
  },
  onMinus(event){
    let goods_id = event.currentTarget.dataset.goodsId;
    let goods_sku_id = event.currentTarget.dataset.goodsSkuId;
    let arr = this.data.GoodsList.data
    let goods_num = 0;
    let deleteGoods = false
    arr.forEach(item => {
      if (item.goods_id == goods_id) {
        goods_num = item.goods_num = item.goods_num - 1
        if(item.goods_num < 1){
          deleteGoods = true;
          item.showMinus = false
        }
      }
    })
    wx.showLoading({
      title: '加载中',
      mask: true
    });
    if(deleteGoods){
      App._post_form('cart/delete', {
        goods_sku_id: goods_id+'_'+goods_sku_id
      }, response => {
        if(response.code == 1){
          this.setData({
            'GoodsList.data': arr
          })
          this.getCartList()
        }
      }, null, () => {
        wx.hideLoading();
      });
    }else{
      App._post_form('cart/sub', {
        goods_id: goods_id,
        goods_num: goods_num,
        goods_sku_id: goods_sku_id,
      }, (response) => {
        if(response.code == 1){
          this.setData({
            'GoodsList.data': arr
          })
          this.getCartList()
        }
      }, null, () => {
        wx.hideLoading();
      });
    }
    
  },
  /**
   * 获取购物车列表
   */
  getCartList() {
    if (!App.getUserId()) return false
    let _this = this;
    App._get('cart/lists', {}, response => {
      if(response.code == 1){
        // 读取购物车中的商品
        let goodsList = _this.data.GoodsList.data
        if(goodsList){
          goodsList.forEach(goods => {
            response.data.goods_list.forEach(cartGoods => {
              if (goods.goods_id == cartGoods.goods_id) {
                goods.goods_num = cartGoods.total_num
                if(cartGoods.total_num > 0){
                  goods.showMinus = true;
                }
              }
            })
          })
          _this.setData({
            'GoodsList.data': goodsList,
            order_price : response.data.order_price  
          })
        }
      }
    });
  },
  // 立即购买
  onCheckout(){
    let _this = this;
    if(_this.data.order_price <= 0){
      App.showError('您还没有选中商品，请先选择商品');
      return false;
    }
    wx.navigateTo({
      url: '../flow/checkout?order_type=cart&cart_ids='
    });
  }
});